﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Group3.Framework.Extensions
{
    public static class ExtensionsString
    {
        public static string IfNullOrEmpty(this string value, string defaultvalue)
        {
            return string.IsNullOrEmpty(value) ? defaultvalue : value;
        }
        public static string IfNullOrWhiteSpace(this string value, string defaultvalue)
        {
            return value.IsNullOrWhiteSpace() ? defaultvalue : value;
        }
        public static bool IsNullOrWhiteSpace(this string value)
        {
            return string.IsNullOrEmpty(value) || value.Replace(" ", "") == "";
        }


        public static string ObjectToString<T>(this T item, string nullvalue, Func<T, string> strfunc)
        {
            if (item == null || strfunc == null)
                return string.IsNullOrEmpty(nullvalue) ? "" : nullvalue;
            else
                return strfunc(item);
        }
        public static int ToInteger(this string data, int defvalue)
        {
            if (data.IsNullOrWhiteSpace())
                return defvalue;
            else
            {
                int ret;
                if (int.TryParse(data, out ret))
                    return ret;
                else
                    return defvalue;
            }
        }

        public static string SubstringValue(this string value, int startindex, int length)
        {
            if (string.IsNullOrEmpty(value))
                return "";
            else if (startindex < 0)
                return value;
            else if (length < 0)
                return "";
            else if (startindex + length > value.Length)
                return value;
            else
                return value.Substring(startindex, length);
        }

        public static string StringReverse(this string value)
        {
            StringBuilder s = new StringBuilder();
            for (int i = value.Length - 1; i > -1; i--)
            {
                s.Append(value[i]);
            }
            return s.ToString();
        }
        public static decimal ToDecimal(this string data)
        {
            decimal ret;
            System.Globalization.CultureInfo cu = System.Globalization.CultureInfo.CurrentCulture;
            data = data.Replace(cu.NumberFormat.NumberDecimalSeparator == "," ? "." : ",", cu.NumberFormat.NumberDecimalSeparator == "," ? "," : ".");
            if (decimal.TryParse(data, out ret))
                return ret;
            else
                return 0;
        }

    }
}
